#!/bin/bash

usage() {
    [[ "$@" != "" ]] && printf "%s\n" "$@"
    cat <<EOF
Usage: $0 [-p path] [uninstall]

Installs the opennic-resolve* files to their locations.
A prefix is used for the binary, configuration and service files
are installed under /etc.

If the first non-option argument is "uninstall", those files are removed again.

-p str  Choose a different prefix. Default: $prefix

-h      This text

EOF
exit 1
}
basename=opennic-resolve
prefix="/usr"

while getopts p:h opt; do
    case $opt in
        p)
            [ -d "$OPTARG" ] && [ -w "$OPTARG" ] || usage "the directory $OPTARG is not writeable or not a directory"
            prefix="$OPTARG"
        ;;
        h|*)  usage
        ;;
    esac
done
shift $((OPTIND-1))

files=(
    "$prefix/bin/$basename"
    "/etc/systemd/system/$basename.service"
    "/etc/systemd/system/$basename.timer"
    "/etc/$basename/$basename.conf"
)

if [[ "${1,,}" == uninstall ]]; then
    echo "Uninstalling..."
    for f in "${files[@]}"; do
        rm -v "$f"
    done
    exit
fi

echo "Installing..."
for f in "${files[@]}"; do
    [[ "${f%/*}" == */?(s)bin ]] && perms=755 || perms=644
    echo install -Dm$perms -t "${f%/*}" "${f##*/}"
    install -Dm$perms -t "${f%/*}" "${f##*/}"
done
